package com.getnerator.web;

import com.getnerator.service.GeneratorService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/generator")
@RequiredArgsConstructor
public class GeneratorController {

    private final GeneratorService generatorService;

    @GetMapping("/tables")
    public List<Map<String, Object>> listTables(@RequestParam(required = false) String keyword){
        return generatorService.listTables(keyword);
    }

    @PostMapping("/generate")
    public Map<String, Object> generate(@RequestBody GenerateReq req) throws Exception{
        return generatorService.generate(req.getTableName(), Boolean.TRUE.equals(req.getForce()));
    }

    // 按指定数据源列表/生成（不改动默认数据源配置）
    @PostMapping("/connect/tables")
    public List<Map<String,Object>> listTablesWithDs(@RequestBody DsReq req){
        return generatorService.listTablesWithDs(req.getUrl(), req.getUsername(), req.getPassword(), req.getKeyword());
    }

    @PostMapping("/connect/generate")
    public Map<String,Object> generateWithDs(@RequestBody DsGenReq req) throws Exception{
        return generatorService.generateWithDs(req.getUrl(), req.getUsername(), req.getPassword(), req.getTableName(), Boolean.TRUE.equals(req.getForce()));
    }

    @Data
    public static class GenerateReq{
        private String tableName;
        private Boolean force;
    }

    @Data
    public static class DsReq{
        private String url;       // jdbc:mysql://host:port/db?params
        private String username;
        private String password;
        private String keyword;   // 可选
    }

    @Data
    public static class DsGenReq extends DsReq{
        private String tableName;
        private Boolean force;
    }
}


